<template>
  <px-dialog v-model="dialogTableVisible" :title="option.title" :width="600">
    <px-form
      ref="ruleFormRef"
      v-loading="loading"
      :model="ruleForm"
      :rules="rules"
      inline
      label-width="120px"
      class="demo-ruleForm"
      :size="formSize"
      status-icon
    >
      <px-form-item label="位置信息" prop="code">
        <px-cascader
          ref="cascaderRef"
          v-model="ruleForm.code"
          filterable
          clearable
          style="width: 300px"
          :options="option.positionCodesList"
          :props="cascaderProps"
          placeholder="请选择位置信息"
          @change="changeCheckArea"
        />
      </px-form-item>
      <px-form-item label="数据来源" prop="dataSource">
        <px-select v-model="ruleForm.dataSource" placeholder="请选择数据来源" style="width: 300px">
          <px-option v-for="item in dataSources" :key="item" :label="item" :value="item" />
        </px-select>
      </px-form-item>
      <px-form-item label="核算模板" prop="templateId">
        <px-select v-model="ruleForm.templateId" placeholder="请选择核算模板" style="width: 300px" @change="getTemplateDetail">
          <px-option v-for="item in templateList" :key="item.id" :label="item.name" :value="item.id" />
        </px-select>
      </px-form-item>
      <px-form-item label="核算边界" prop="dto">
        <!-- <px-select v-model="ruleForm.dto" placeholder="核算边界">
          <px-option v-for="item in treeDTO" :key="item.id" :label="item.label" :value="item.id" />
        </px-select> -->
        <px-cascader
          ref="treeDTORef"
          v-model="ruleForm.dto"
          filterable
          clearable
          style="width: 300px"
          :options="treeDTO"
          :props="treeDTOProps"
          placeholder="请选择核算边界"
          @change="changeTreeDTO"
        />
      </px-form-item>
      <px-form-item label="设施活动" prop="facilitys">
        <px-select
          v-model="ruleForm.facilitys"
          multiple
          collapse-tags
          collapse-tags-tooltip
          :max-collapse-tags="3"
          placeholder="请选择设施活动"
          style="width: 300px"
          value-key="facilityId"
          @change="changeFacilitys"
        >
          <px-option v-for="item in facilityList" :key="item.facilityId" :label="item.facilityName" :value="item" />
        </px-select>
      </px-form-item>
      <px-form-item label="绑定设施活动" prop="transIdList">
        <px-tag
          v-for="(item, index) in ruleForm.transIdList"
          :key="item.facilityId"
          class="mx-1 mb-1"
          closable
          type="info"
          @close="handleClose(index)"
        >
          {{ item.facilityName }}
        </px-tag>
      </px-form-item>
    </px-form>
    <template #footer>
      <span class="dialog-footer">
        <px-button @click="cancelHandler">取消</px-button>
        <px-button type="primary" :loading="loading" @click="submitHandler"> 确认 </px-button>
      </span>
    </template>
  </px-dialog>
</template>
<script setup lang="ts">
defineOptions({
  name: "GAS_TASK_MONITORINGMANAGE_EQP_CHECKOUT_ADD"
});

import { ref, reactive, onMounted } from "vue";
import type { FormInstance, FormRules } from "px-ui";
import { useThrottleFn } from "@vueuse/core";
import { throttleDelay as delay } from "@/utils/constant";
import { accountingReporttemplateList } from "@/api/doubleCarbonManage/accountingManage";
import { accountingTemplatedetail } from "@/api/doubleCarbonManage/accountingBoundary";
import { updateDigitaltwinsConfig } from "@/api/doubleCarbonManage/carbonAccounting";

interface Props {
  option: {
    title: string;
    // 弹框类型 add 新增   edit 编辑 detail 详情
    type: "add" | "edit" | "detail";
    positionCodesList: any;
    data: any;
  };
}

const props = withDefaults(defineProps<Props>(), {});
const dialogTableVisible = defineModel({ type: Boolean, default: false });

const loading = ref(false);
interface RuleForm {
  code: string;
  dataSource: string;
  templateId: number;
  dto: string;
  facilitys: string[];
  transIdList: any[];
  path: string;
  pathName: string;
}
const formSize = ref("default");
const ruleFormRef = ref<InstanceType<typeof FormInstance>>();
const ruleForm = reactive<RuleForm>({
  code: "",
  dataSource: "双碳",
  templateId: null,
  dto: "",
  facilitys: [],
  transIdList: [],
  path: "",
  pathName: ""
});
const dataSources = [
  "双碳"
  // {label:'能源',id:2}, // 暂时无
];
// 获取核算模板
const templateList = ref([]);
async function getTemplateList() {
  const res = await accountingReporttemplateList({});
  templateList.value = res;
}
// 获取核算边界&设施活动
const treeDTO = ref([]);
const facilityList = ref([]);
async function getTemplateDetail(params) {
  const res = await accountingTemplatedetail({ id: params }).catch(() => {
    ruleForm.dto = "";
    ruleForm.facilitys = [];
    ruleForm.transIdList = [];
    treeDTO.value = [];
    facilityList.value = [];
  });
  ruleForm.dto = "";
  ruleForm.facilitys = [];
  ruleForm.transIdList = [];
  treeDTO.value = [res.treeDTO];
  facilityList.value = [];
}
const treeDTOProps = {
  children: "children",
  label: "name",
  value: "id"
  // checkStrictly: true
};
const treeDTORef = ref();
function changeTreeDTO(val) {
  console.log(`output->val`, val);
  const checkedNodes = treeDTORef.value.getCheckedNodes();
  console.log(`output->checkedNodes`, checkedNodes);
  if (checkedNodes.length <= 0) {
    ruleForm.facilitys = [];
    treeDTORef.value.togglePopperVisible();
    return;
  }
  ruleForm.facilitys = [];
  facilityList.value = checkedNodes[0].data.list;
  console.log(`output->facilityList.value`, facilityList.value);
  treeDTORef.value.togglePopperVisible();
}
// 去重
function removeDuplicatesById(arr) {
  return [...new Map(arr.map(item => [item.facilityId, item])).values()];
}
function changeFacilitys(val) {
  console.log(`changeFacilitys->val`, val);
  ruleForm.transIdList.push(...val);
  ruleForm.transIdList = removeDuplicatesById(ruleForm.transIdList);
}
const handleClose = (index: number) => {
  ruleForm.transIdList.splice(index, 1);
};
const cascaderProps = {
  children: "children",
  label: "name",
  value: "code",
  checkStrictly: true
};
const cascaderRef = ref();
// 巡检区域改变
const changeCheckArea = val => {
  console.log(`output->val`, val);
  if (!val) return;
  ruleForm.path = "";
  ruleForm.pathName = "";
  ruleForm.code = val && val.length > 0 ? val[val.length - 1] : "";
  cascaderRef.value.togglePopperVisible();
  const checkedNodes = cascaderRef.value.getCheckedNodes();
  if (checkedNodes.length >= 0) {
    ruleForm.path = checkedNodes[0].data.path;
    ruleForm.pathName = checkedNodes[0].data.zhPath;
  }
};

const rules = reactive({
  code: [{ required: true, message: "请选择位置信息", trigger: "change" }],
  dataSource: [{ required: true, message: "请选择数据来源", trigger: "change" }],
  templateId: [{ required: true, message: "请选择核算模板", trigger: "change" }],
  // dto: [{ required: true, message: "请选择核算边界", trigger: "change" }],
  transIdList: [{ required: true, message: "请绑定设施活动", trigger: "change" }]
});

const emits = defineEmits(["submit"]);

onMounted(async () => {
  await getTemplateList();
  if (props.option.type === "edit") {
    console.log(`output->props.option.data`, props.option.data);
    const data = props.option.data;
    ruleForm.dataSource = data.dataSource;
    const pathList = data.path.split("@");
    ruleForm.code = pathList;
    console.log(`output->pathList`, pathList);
    ruleForm.templateId = data.templateId;
    await getTemplateDetail(ruleForm.templateId);
    ruleForm.path = data.path;
    ruleForm.pathName = data.pathName;
    ruleForm.transIdList = data.dataContent;
  }
});

const cancelHandler = () => {
  dialogTableVisible.value = false;
};

// 提交
const submitHandler = useThrottleFn(async () => {
  if (!ruleFormRef.value) return;
  await ruleFormRef.value.validate(async (valid, fields) => {
    if (valid) {
      loading.value = true;
      const params = {
        ...ruleForm,
        transIdList: ruleForm.transIdList.map(e => e.facilityId),
        updateByName: JSON.parse(localStorage.getItem("userInfo")).username
      };
      delete params.dto;
      delete params.facilitys;
      console.log(`output->params`, params);
      try {
        if (props.option.type === "add") {
          await updateDigitaltwinsConfig(params);
        } else if (props.option.type === "edit") {
          if (Array.isArray(params.code)) {
            params.code = params.code[params.code.length - 1];
          }
          await updateDigitaltwinsConfig({ id: props.option.data.id, ...params });
        }
        loading.value = false;
        emits("submit");
        dialogTableVisible.value = false;
      } catch (error) {
        loading.value = false;
      }
    } else {
      console.error("error submit!", fields);
    }
  });
}, delay);
</script>

<style lang="scss" scoped>
:deep(.px-form-item) {
  width: 100%;
}
</style>
